using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ICP_MS.Plugin.Experiment;

public class SeqExperiment
{
	public List<ExperimentDatasSeq> DatasSeqs = new List<ExperimentDatasSeq>();

	public List<SamplesInfos> Samples = new List<SamplesInfos>();

	public int sampleIndex = 0;

	public bool autoSample = false;

	public int experimentIndex = 0;

	public bool IsRun = false;

	public int currentStatus { get; set; }

	public event EventHandler IsAutoSamplerChangedEvent = null;

	public event EventHandler analyseFinish = null;

	public bool PreRun()
	{
		foreach (ExperimentDatasSeq data in DatasSeqs)
		{
			data.experiment.AutosampleTable.autoSample = autoSample;
			if (!data.experiment.PreRun())
			{
				return false;
			}
		}
		return true;
	}

	public void StartRun()
	{
		IsRun = true;
		Task.Factory.StartNew(delegate
		{
			foreach (SamplesInfos current in Samples)
			{
				if (current.status == 0)
				{
					bool flag = false;
					for (int i = 0; i < DatasSeqs.Count; i++)
					{
						FormExperiment.IsRun = true;
						ExperimentDatasSeq experimentDatasSeq = DatasSeqs[i];
						if (i == 0)
						{
							experimentDatasSeq.experiment.IsFirst = true;
						}
						else
						{
							experimentDatasSeq.experiment.IsFirst = false;
						}
						experimentIndex = i;
						SamplesInfos samplesInfos = new SamplesInfos
						{
							label = current.label,
							inter = current.inter,
							predilution = current.predilution,
							mass = current.mass,
							volume = current.volume,
							report = current.report,
							mains = current.mains,
							surveys = current.surveys,
							type = current.type,
							blank = current.blank,
							curveId = current.curveId,
							rackNumber = current.rackNumber,
							vialNumber = current.vialNumber,
							ZDepth = current.ZDepth,
							guid = experimentDatasSeq.experiment.Scan.sampleIndex++
						};
						experimentDatasSeq.experiment.Samples.Add(current);
						experimentDatasSeq.experiment.SeqSampleAddNotify();
						if (experimentDatasSeq.experiment.StartRun(current) != 0)
						{
							flag = true;
							break;
						}
						if (!IsRun)
						{
							break;
						}
					}
					if (!IsRun || flag)
					{
						break;
					}
				}
			}
			IsRun = false;
			FormExperiment.IsRun = false;
			if (this.analyseFinish != null)
			{
				this.analyseFinish(null, null);
			}
			if (autoSample)
			{
				AutoSampler.Instance.Rinse();
			}
		});
	}

	public void StopRun()
	{
		foreach (ExperimentDatasSeq data in DatasSeqs)
		{
			ExperimentDatas experiment = data.experiment;
			if (experiment.IsRun)
			{
				experiment.StopRun();
				experiment.IsRun = false;
			}
		}
	}

	public void OnSamplerChanged()
	{
		if (this.IsAutoSamplerChangedEvent != null)
		{
			this.IsAutoSamplerChangedEvent(null, null);
		}
	}
}
